package com.meowcook.service.impl;

import com.meowcook.exception.AppException;
import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import com.meowcook.dao.CommentMapper;
import com.meowcook.dao.RecipeMapper;
import com.meowcook.dao.ReplyMapper;
import com.meowcook.mapper.ReplyPojoMapper;
import com.meowcook.pojo.dto.ReplyDTO;
import com.meowcook.pojo.dto.ReplyListDTO;
import com.meowcook.pojo.po.Comment;
import com.meowcook.pojo.po.Recipe;
import com.meowcook.pojo.po.Reply;
import com.meowcook.pojo.vo.ReplyVO;
import com.meowcook.service.IReplyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-05-18
 * Time: 13:24
 */
@Service
public class ReplyServiceImpl implements IReplyService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private RecipeMapper recipeMapper;
    @Resource
    private ReplyMapper replyMapper;
    @Resource
    private ReplyPojoMapper replyPojoMapper;
    @Override
    public void reply(ReplyDTO replyDTO) {
        // 数据转化
        Reply reply = replyPojoMapper.toPo(replyDTO);
        // 调用dao
        int row = replyMapper.insertSelective(reply);
        if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        // 同步评论的回复数
        Comment comment = commentMapper.selectByPrimaryKey(reply.getCommentId());
        Comment updateComment = new Comment();
        updateComment.setId(comment.getId());
        updateComment.setReplyCount(comment.getReplyCount() + 1);
        int row1 = commentMapper.updateByPrimaryKeySelective(updateComment);
        if (row1 != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        // 同步食谱的评论数
        Recipe recipe = recipeMapper.selectByPrimaryKey(reply.getRecipeId());
        Recipe updateRecipe = new Recipe();
        updateRecipe.setId(recipe.getId());
        updateRecipe.setCommentCount(recipe.getCommentCount() + 1);
        int row2 = recipeMapper.updateByPrimaryKeySelective(updateRecipe);
        if (row2 != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
    }

    @Override
    public List<ReplyVO> selectByCommentId(ReplyListDTO replyListDTO) {
        List<Reply> replies = replyMapper.selectByCommentId(replyListDTO);
        return replyPojoMapper.toVO(replies);
    }
}
